<?php

/**
 * 开发者Domain 类
 * @author: 喵了个咪  <wenzhenxi@vip.qq.com> 2015-07-23
 */
class Domain_Validation {

    /**
     * 验证权限
     */
    public function validation($apiname, $uId) {

        //通过Id获取角色
        $Model_ManageRole = new Model_ManageRole();
        $rs               = $Model_ManageRole->getManagIdListByRoleIdList($uId);
        $RoleIdList       = array();
        foreach ($rs as $v) {
            $RoleIdList[] = $v['rId'];
        }
        //过滤角色
        $Model_Role = new Model_Role();
        $rs         = $Model_Role->filterId($RoleIdList);
        $RoleIdList = array();
        foreach ($rs as $v) {
            $RoleIdList[] = $v['rId'];
        }
        //获取权限ID列表
        $Model_RolePrivilege = new Model_RolePrivilege();
        $rs                  = $Model_RolePrivilege->getpriIdByPrivilegeIdlist($RoleIdList);
        $PrivilegeIdList     = array();
        foreach ($rs as $v) {
            $PrivilegeIdList[] = $v['priId'];
        }
        //过滤权限
        $Model_Privilege = new Model_Privilege();
        $rs              = $Model_Privilege->filterId($PrivilegeIdList);
        $PrivilegeIdList = array();
        foreach ($rs as $v) {
            $PrivilegeIdList[] = $v['priId'];
        }
        //通过权限获得APIListID
        $Model_PrivilegeApi = new Model_PrivilegeApi();
        $rs                 = $Model_PrivilegeApi->getpriIdByapiId($PrivilegeIdList);
        $ApiIdList          = array();
        foreach ($rs as $v) {
            $ApiIdList[] = $v['apiId'];
        }
        //通过接口名和权限ID列表过滤
        $Model_Api = new Model_Api();
        $rs        = $Model_Api->validation($apiname, $ApiIdList);
        if (!$rs) {
            throw new PhalApi_Exception_BadRequest(T('No Privilege'));
        }
        $ApiIdList = array();
        foreach ($rs as $v) {
            $ApiIdList[] = $v['apiId'];
        }
        //通过项目名获取项目ID
        $Model_Project = new Model_Project();
        $ProId         = $Model_Project->getNameById(DI()->config->get('app.objectname'));
        if (!$ProId) {
            throw new PhalApi_Exception_BadRequest(T('No Project'));
        }
        //通过项目Id 和 用户API Id 验证
        $Model_ProjectApi = new Model_ProjectApi();
        $rs               = $Model_ProjectApi->getApiIdListOrProId($ApiIdList, $ProId);
        if (!$rs) {
            throw new PhalApi_Exception_BadRequest(T('No Privilege'));
        }
    }
}